package com.thx.common.util;

import com.thx.common.web.WebConstant;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * 应用上下文信息，一般从配置文件加载，同时支持从.properties和.xml两种文件中加载配置
 *
 * <p/>
 * 若两种文件中有重复的参数定义，以.xml文件中的为有效配置.
 */
public class AppContext {

  private static Log log = LogFactory.getLog(AppContext.class);

  // properties方式配置的参数文件
  private static final String CONFIG_PROPERTIES_FILE = "app-config.properties";

  // xml配置的参数文件
  private static final String CONFIG_XML_FILE = "app-config.xml";

  private static Properties CONFIG = null;

  private static int perPage = 15;

  public static final String CURRENT_COM_ID = "com.thx.saas.companyId";

  private static synchronized void load() {
    if (CONFIG == null) {
      URL propUrl = Loader.getResource(CONFIG_PROPERTIES_FILE);
      URL xmlUrl = Loader.getResource(CONFIG_XML_FILE);
      InputStream propIn = null;
      InputStream xmlIn = null;

      try {
        CONFIG = new Properties();

        if (propUrl != null) {
          propIn = propUrl.openStream();
          CONFIG.load(propIn);
        }

        if (xmlUrl != null) {
          xmlIn = xmlUrl.openStream();
          CONFIG.loadFromXML(xmlIn);
        }

        initDefaultParaments();

      } catch (IOException ex) {
        log.error("加载配置文件【" + CONFIG_PROPERTIES_FILE + "】异常！", ex);
      } finally {
        try {
          if (propIn != null) {
            propIn.close();
          }
          if (xmlIn != null) {
            xmlIn.close();
          }
        } catch (IOException ex) {
          log.error("关闭输入流异常", ex);
        }
      }
    }
  }

  private static void initDefaultParaments() {
    try {
      perPage = Integer.parseInt(CONFIG.getProperty(WebConstant.PER_PAGE_KEY, "15"));
      // TODO 其他参数

    } catch (Exception ex) {
      perPage = 15;
    }

  }

  /**
   * 取属性值.
   *
   * @param key 属性key
   * @return 该属性配置的值
   */
  public static String getProperties(String key) {
    if (CONFIG == null) {
      load();
    }
    return CONFIG.getProperty(key);
  }

  /**
   * 获取 perPage 属性的值.
   *
   * @return perPage 每页翻页数量
   */
  public static int getPerPage() {
    if (CONFIG == null) {
      load();
    }
    return perPage;
  }

  /**
   * 获取当前的公司id.
   *
   * @return 当前环境中的公司id
   */
  public static String getCurrentComId() {
    return (String) ThreadLocalContext.get(CURRENT_COM_ID);
  }

  /**
   * 设定当前环境的公司id.
   *
   * @param comId 公司标识
   */
  public static void setCurrentComId(String comId) {
    ThreadLocalContext.set(CURRENT_COM_ID, comId);
  }

}
